import React from 'react';
import { useRequest } from 'umi';
import { getTreeByCompanyData, getTreeByDepartData } from '../service';
import {
  getCompanyID,
  getTenantID,
  getUserDepID,
  requestFunCompon,
} from '@/utils';

const useDpmData = (curRes: any) => {
  const { run, data, loading } = useRequest(
    () => {
      if (!!curRes['/departmentController/getTreeByCompany']) {
        return getTreeByCompanyData({
          companyID: getCompanyID(),
          dicTypeIds: `${getTenantID()}1003`,
        });
      } else if (!!curRes['/departmentController/getTreeByDepart']) {
        return getTreeByDepartData({
          id: getUserDepID(),
          dicTypeIds: `${getTenantID()}1003`,
        });
      }
    },
    {
      manual: false, //页面初始请求为true
    },
  );

  let dataSource = React.useMemo(() => {
    // return treeData
    if (data && data?.msgFlag) {
      return [data?.obj];
    } else {
      return [];
    }
  }, [data]);

  return {
    dataSource,
    run,
    loading,
  };
};

// 获取部门详情
const getDeptDetailInfo = (resObj: any) => {
  const deptDetail = useRequest(
    () => {
      let reqUrl = `/departmentController/getDepartmentByID/${resObj?.id}`;
      return requestFunCompon('GET', reqUrl);
    },
    {
      manual: resObj?.id ? false : true,
    },
  );

  let detailInfo = React.useMemo(() => {
    if (deptDetail?.data && deptDetail?.data?.msgFlag) {
      return deptDetail?.data?.obj;
    } else {
      return null;
    }
  }, [deptDetail?.data]);

  return {
    deptDetailInfo: detailInfo,
    deptLoading: deptDetail?.loading,
    deptRun: deptDetail?.run,
  };
};

export { useDpmData, getDeptDetailInfo };
